package com.n.passwordbook;

import com.n.passwordbook.LaunchWindow.LaunchWindow;
import com.n.passwordbook.LaunchWindow.TmpDataHelper;
import com.n.passwordbook.PasswordBook.PasswordBook;
import com.n.passwordbook.Utils.EnableDragWindow;
import com.n.passwordbook.Utils.Helper;
import com.n.passwordbook.Utils.Settings;
import com.n.passwordbook.Utils.WindowHelper;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

import java.net.URL;

public class Launcher extends Application
{
    public static void main(String[] args)
    {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception
    {
        Helper.checkAppNOTStarted();
        TmpDataHelper.MainWindowPreloadThread.start();

        Platform.setImplicitExit(false);

        //加载fxml
        FXMLLoader LaunchWindowLoader = new FXMLLoader();
        URL LaunchWindowURL = getClass().getResource("LaunchWindow/LaunchWindow.fxml");
        LaunchWindowLoader.setLocation(LaunchWindowURL);

        FXMLLoader PageLoader = new FXMLLoader();

        if (Settings.checkIfSettingsExist() && PasswordBook.loadPasswordBook(Settings.getPasswordPath()))
        {
            URL PageURL = getClass().getResource("LaunchWindow/LoginPage.fxml");
            PageLoader.setLocation(PageURL);
            TmpDataHelper.NowPage = PageLoader.load();
        }
        else
        {
            URL PageURL = getClass().getResource("LaunchWindow/FirstLaunch.fxml");
            PageLoader.setLocation(PageURL);
            TmpDataHelper.NowPage = PageLoader.load();
        }

        LaunchWindow launchWindow = new LaunchWindow();
        LaunchWindowLoader.setController(launchWindow);
        WindowHelper.MainController = LaunchWindowLoader.getController();
        Pane startPane = LaunchWindowLoader.load();

        //准备呈现窗口
        Scene mainScene = new Scene(startPane);
        primaryStage.setScene(mainScene);
        primaryStage.initStyle(StageStyle.UNDECORATED);//设定窗口无边框
        primaryStage.setResizable(false);
        primaryStage.getIcons().add(Helper.Icon);
        primaryStage.setIconified(false);
        primaryStage.setOnCloseRequest(e -> System.exit(0));
        new EnableDragWindow(primaryStage, mainScene);//允许拖动窗口
        WindowHelper.MainContainer = startPane;
        WindowHelper.MainContainerTypeString = startPane.getClass().getTypeName();
        WindowHelper.MainScene = mainScene;
        WindowHelper.MainStage = primaryStage;

        Settings.SetStartTimes();
        primaryStage.setAlwaysOnTop(Settings.getTopMost());
        Helper.StartTimes = Settings.getStartTimes();
        Settings.saveSettingsFile();

        primaryStage.show();

        launchWindow.windowShowAnimation();
    }
}